package com.gopay.bis.manager.bank.ebank;

import java.io.UnsupportedEncodingException;
import java.util.Map;


import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.spdb.ebank.SpdbMessage;
import com.gopay.common.domain.user.mcc.UserMccTransformReq;
import com.gopay.common.domain.user.mcc.UserMccTransformRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.mcc.manager.UserMccTransformManager;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

/**
 * @SpdbB2bManager.java
 * @author wanggang
 * @2013-12-12 下午1:49:06 www.gopay.com.cn Inc.All rights reserved.
 */
public class SpdbB2bManager implements BankManagerRemoteService {

	@Resource(name = "spdbConfig")
	private Map<String, String> spdbConfig;
	
	@Resource(name = "spdbB2bBankServiceClient")
	private BankService spdbB2bBankServiceClient;
	
	@Resource(name = "userMccTransformManager")
    private UserMccTransformManager userMccTransformManager;

	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		SpdbMessage message = (SpdbMessage) msg;
		message.setBankOrderId(TransUtil.processOrderIdTo12Digit(msg.getOrderId()));
		message.setBankUrl(message.getPayUrl());
		message.setTermCode((String) spdbConfig.get("SPDB.TERMCODE"));
		message.setMercCode(message.getMerID());
		message.setMercUrl(message.getPayRuturnUrl());
		message.setTranAbbr((String) spdbConfig.get("SPDB.B2B.TRANABBR"));
		//新增二级商户号报备
		UserMccTransformReq userM = new UserMccTransformReq();
        userM.setBankCode(BankConstants.BANK_LOGO_SPDB);
        userM.setCustId(msg.getSpecial2());
        UserMccTransformRes userRes = userMccTransformManager.graspUserMccInfo(userM);
        
        if(userRes == null){
            if((BankConstants.GOPAY_CHONGZHI_CUSTID).equals(msg.getSpecial2())){
                message.setSubMercFlag((String) spdbConfig.get("SPDB.SUBMERC.XUNI"));
                message.setSubMercName(BankConstants.GOPAY_NAME);
                message.setSubMercGoodsName("国付宝充值");
            }
        }else{
            if(BankConstants.GOPAY_MCC_CODE.equals(userRes.getGopayMccCode())){
                message.setSubMercFlag((String) spdbConfig.get("SPDB.SUBMERC.SHIWU"));
                message.setSubMercName("（");
                message.setSubMercGoodsName("平台服务）");
            }else{
             // 非p2p商户信息报备
                message.setSubMercFlag((String) spdbConfig.get("SPDB.SUBMERC.SHIWU"));
                message.setSubMercName(userRes.getCorpName());
                message.setSubMercGoodsName(userRes.getBankMccDesc());
                if (BankConstants.BANK_MCC_CODE_7375.equals(userRes.getBankMccCode())
                        || BankConstants.BANK_MCC_CODE_4814.equals(userRes.getBankMccCode())
                        || BankConstants.BANK_MCC_CODE_4816.equals(userRes.getBankMccCode())) {
                    // 信息检索服务、计算机网络、电信服务归属于消费虚拟类
                    message.setSubMercFlag((String) spdbConfig.get("SPDB.SUBMERC.XUNI"));
                }
                
            }
        }
		// 报文明文
		String plainMessage = buildMessage(message);
		message.setPlainMessage(plainMessage);
		BankLogUtils.printB2BManagerSignSendLog(message);
		String signMessage;		
		signMessage = (String) this.spdbB2bBankServiceClient.sign(message);		
		message.setSignMessage(signMessage);
		BankLogUtils.printB2BManagerSignReturnLog(message);
		return message;
	}

	@Override
	public Object verify(BaseMessage baseMessage) throws GopayException {
		SpdbMessage message = (SpdbMessage) baseMessage;
		boolean isVerify;	
		isVerify = (Boolean) this.spdbB2bBankServiceClient.verify(message);
		return isVerify;
	}

	@Override
	public Object query(Object obj) throws GopayException {
		SpdbMessage message = (SpdbMessage) obj;
		message.setMercCode(message.getMerID());
		message.setoTranAbbr((String) spdbConfig.get("SPDB.B2B.TRANABBR"));
		message.setTransName((String) spdbConfig.get("SPDB.TRANABBR.QUERY"));
		message.setPlainMessage(buildQuery(message));
		BankLogUtils.printB2BManagerQuerySendLog(message, "");	
		message = (SpdbMessage) this.spdbB2bBankServiceClient.query(message);
		message.setOutStlmCd(BankConstants.BANK_LOGO_SPDB);
		BankLogUtils.printB2BManagerQueryReturnLog(message);
		return message;
	}

	/**
	 * 构建报文
	 * 
	 * @param message
	 * @return
	 * @throws GopayException 
	 */
	private String buildMessage(SpdbMessage message) throws GopayException {
	    StringBuffer sb = new StringBuffer();
	    try{	       
	        sb.append("TranAbbr=").append(message.getTranAbbr()).append("|");
	        sb.append("MasterID=").append(message.getMasterID()).append("|");
	        sb.append("MercDtTm=").append(message.getOrderDate()).append("|");
	        sb.append("TermSsn=").append(message.getBankOrderId()).append("|");
	        sb.append("OSttDate=").append(message.getoSttDate()).append("|");
	        sb.append("OAcqSsn=").append(message.getoAcqSsn()).append("|");
	        sb.append("MercCode=").append(message.getMercCode()).append("|");
	        sb.append("TermCode=").append(message.getTermCode()).append("|");
	        sb.append("TranAmt=").append(message.getAmount().toString()).append("|");
	        sb.append("Remark1=").append(message.getRemark1()).append("|");
	        sb.append("Remark2=").append(message.getRemark2()).append("|");
	        sb.append("MercUrl=").append(message.getMercUrl()).append("|");
	        sb.append("SubMercFlag=").append(message.getSubMercFlag()).append("|");
	         if (StringUtils.isBlank(message.getSubMercName())) {
	             sb.append("SubMercName=").append(message.getSubMercName()).append("|");
	         } else {
	             sb.append("SubMercName=").append(java.net.URLEncoder.encode(message.getSubMercName(), "GBK")).append("|");
	         }
	         if (StringUtils.isBlank(message.getSubMercGoodsName())) {
	             sb.append("SubMercGoodsName=").append(message.getSubMercGoodsName());
	         } else {
	             sb.append("SubMercGoodsName=").append(java.net.URLEncoder.encode(message.getSubMercGoodsName(),"GBK"));
	         }
	        
	    }catch (UnsupportedEncodingException e) {
            BankLogUtils.printB2BSignExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6028);
        }
	    return sb.toString();
	}

	private String buildQuery(SpdbMessage message) {
		StringBuffer sb = new StringBuffer();
		sb.append("MercCode=").append(message.getMercCode()).append("|");
		sb.append("OTranAbbr=").append(message.getoTranAbbr()).append("|");
		sb.append("TermSsn=").append(message.getBankOrderId());
		return sb.toString();
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}
}
